
<template>
  <div class="campus-page">
    <div class="input-card">
      当前模式：{{ type === 1 ? '只读模式' : (type === 2 ? '编辑模式' : '新建模式') }}
      <div >
        <template v-if="type === 1">
          <el-button type="primary" round size="mini" @click="startPolygon(3)">新建区域</el-button>
          <el-button type="primary" round size="mini" @click="startPolygon(2)">编辑模式</el-button>
        </template>
        <el-button v-if="type !== 1" type="info" size="mini" round plain @click="cancelPolygon()">取消</el-button>
        <el-button v-if="type === 2" type="primary" size="mini" round @click="closePolygon()">完成</el-button>
      </div>
    </div>
    <el-alert title="操作说明：" type="info" show-icon>
      <div v-show="type === 1">
       可点击右侧`编辑模式`按钮进入编辑模式,点击`新建区域`按钮圈选新的区域
      </div>
      <div v-show="type === 2">
        <span class="red">鼠标左键单击</span>
        网格区域，可选中当前区域，可进行编辑区域操作，再点保存按钮结束操作。鼠标右键选择区域进行删除。
      </div>
      <div v-show="type === 3">
        点击新建按钮，通过<span class="red">鼠标左键描点</span>构建网格区域，最后以
        <span class="red">鼠标右键单击</span> 结束网格区域，最后点击保存按钮，完善信息即可完成新建功能。
      </div>
    </el-alert>
    <div id="campusMap"></div>
  </div>
</template>

<script>
/* eslint-disable */
import AMapLoader from "@amap/amap-jsapi-loader";
var polyEditor = "";
// let AMap = null
window.oncontextmenu = function (e) {
  e.preventDefault();
};
export default {
  props: {
    schooleName: String,
    dzName1: Array,
    visible1: Boolean,
    datas: String,
    statusType:String
  },
  data() {
    return {
      satellite: true, //卫星地图
      flagText: true, //弹出框编辑状态
      type: 1,
      okText: "编辑", //弹出框文本
      visible: false,
      labelCol: { style: { width: "130px" } },
      formState: {
        name: "123",
      },
      rules: {
        name: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
      },
      area: "", //区域面积大小
      infoWindow: "",
      infoWindow2: "",
      polygonList: [],
      pathArr: [],
      pathArrLast: [],
      isCancelHandle: false,
      currentEditorPolygon: null
    };
  },
  watch: {
  },
  mounted() {
  },
  methods: {
    initData(data) {
      if (data) {
        this.pathArr = JSON.parse(data);
      }else{
        this.pathArr=[]
      }
      this.initMap();
    },
    onSubmit() {
      if (this.flagText) {
        this.flagText = false;
        this.okText = "保存";
      } else {
        this.$refs.formRef.validate().then(async () => {
          this.okText = "编辑";
          this.flagText = true;
        }).catch((error) => {
          console.log("error", error);
        });
      }
    },
    async initMap() {
      await AMapLoader.load({
        key: "a8495fcc75776a9eb1a4f3e907f0b84e", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.PolygonEditor",
          "AMap.Autocomplete",
          "AMap.PlaceSearch",
          "AMap.Scale",
          "AMap.OverView",
          "AMap.ToolBar",
          "AMap.MapType",
          "AMap.PolyEditor",
          "AMap.CircleEditor",
          "AMap.Geolocation",
          "AMap.Geocoder",
          "AMap.Polygon",
          "AMap.AMapUI",
          "AMap.InfoWindow", //新建窗体
          "AMap.GeometryUtil", //区域面积
          "AMap.TileLayer.Satellite",
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map("campusMap", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 15, //初始化地图级别
            disableDoubleClickZoom: false,
            // center:this.pathArr?this.pathArr[0].key[0]:''
            // center: [107.474262, 32.005631],
            center: window.location_name_school.split(',') || [116.407387,39.904179],
          });
          // 设置缩放级别最小单位为1
          // this.map.setZoom(Math.max(1, this.map.getZoom()));
          // 监听地图缩放事件
          this.map.on("zoomend", () => {
            const zoom = this.map.getZoom();
            console.log(zoom);
            // 在这里可以执行你需要的操作，比如更新数据或发送请求等
          });
          // 添加卫星图层
          if (!this.satellite) {
            const tileLayer = new AMap.TileLayer.Satellite({
              map: this.map,
            });
            tileLayer.show();
          }
          this.map.setFitView();
          // 数据格式化
          this.drawPolygon()
          // 创建自定义信息窗体
          this.infoWindow = new AMap.InfoWindow({
            content: this.$refs.conts, // 替换为你的自定义信息窗体内容
            // position: [116.397428, 39.90923], // 替换为你的信息窗体位置坐标点
            offset: new AMap.Pixel(0, -10), // 信息窗体相对于定位点的偏移量
          });
          this.infoWindow2 = new AMap.InfoWindow({
            content: this.$refs.conts2, // 替换为你的自定义信息窗体内容
            // position: [116.397428, 39.90923], // 替换为你的信息窗体位置坐标点
            offset: new AMap.Pixel(0, 10), // 信息窗体相对于定位点的偏移量
          });
          polyEditor = new AMap.PolygonEditor(this.map);
          this.initEditor();
          polyEditor.close();
        }).catch((e) => {
          console.error(e);
        });
    },
    drawPolygon() {
      this.map.remove(this.polygonList);
      this.polygonList = [];
      for (const pathVal of this.pathArr) {
        if (!pathVal) {
          continue;
        }
        const path = [];
        for (const pathValKey of pathVal.key) {
          path.push(new AMap.LngLat(pathValKey[0], pathValKey[1]));
        }
        this.addPolygon(path, pathVal.timestamp);
      }
    },
    //创建多边形-函数封装;
    addPolygon(path, id) {
      let that = this
      const polygon = new AMap.Polygon({
        map: this.map,
        path: path,
        strokeColor: '#2b8cbe',
        strokeWeight: 4,
        strokeOpacity: 0.2,
        fillOpacity: 0.6,
        fillColor: that.statusType === 'safe' ? '#1791fc' : '#d43924',
        zIndex: 50,
        bubble: true,
        dataForms: id
      });
      this.polygonList.push(polygon);
      // // 多边形覆盖物上点击显示窗体;
      polygon.on('click', function (e) {
      	//打开编辑
      	if (that.type === 2) {
          that.currentEditorPolygon = polygon
      		polyEditor.setTarget(polygon) //打开编辑
      		polyEditor.open() //打开编辑
      		that.infoWindow.close()
      	}
      })
      polygon.on('rightclick', (e) => {
        if (that.type === 1) return
        const bodyDom = document.querySelector('.el-drawer__body')
        const bodyScroll = {
          y: bodyDom.scrollTop,
          x: bodyDom.scrollLeft
        }
        that.$confirm('确定删除该区域么?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (that.currentEditorPolygon === polygon) {
            polyEditor.setTarget()
          }
          polygon.remove();
          const index = that.polygonList.findIndex(item => item === polygon)
          that.pathArr.splice(index, 1)
          bodyDom.scrollTo(bodyScroll.x, bodyScroll.y)
        }).catch(() => {
          bodyDom.scrollTo(bodyScroll.x, bodyScroll.y)
        });
      })
      //鼠标高亮效果
      polygon.on('mouseover', ()=> {
      	polygon.setOptions({
      		cursor: 'pointer'
      	})
      })
    },
    initEditor() {
      const that = this
      // add 是区域画完后鼠标右键保存事件。
      polyEditor.on('add', (data) => {
        this.pathArr.push({
          key: data.target._opts.path,
              mapId: data.target._amap_id,
        })
        polyEditor.setTarget();
        that.drawPolygon();
        that.closePolygon();
      });
      //end 是结束编辑按钮
      polyEditor.on('end', (data) => {
        if (this.isCancelHandle) {
          return;
        }
        let obj = {
          key: data.target._opts.path,
          mapId: data.target._amap_id,
        };
        let isRepeat = this.polygonList.some((item, index) => {
          if (item._amap_id === obj.mapId) {
            this.pathArr[index] = obj;
            return true;
          }
        });
        if (!isRepeat) {
          this.pathArr.push(obj);
        }
        console.log(this.pathArr, "最终的点位合集"); // 最终的点位合集
      });
      polyEditor.open(); // 进入组件就可以编辑
      return polyEditor;
    },
    //新建
    createPolygon() {
      this.type = 3;
      polyEditor.close();
      polyEditor.setTarget();
      polyEditor.open();
    },
    //结束编辑
    closePolygon() {
      this.visible = true;
      this.type = 1;
      // 关闭
      polyEditor.close();
    },
    cancelPolygon() {
      if (this.type === 3) {
        this.closePolygon()
        return
      }
      const bodyDom = document.querySelector('.el-drawer__body')
      const bodyScroll = {
        y: bodyDom.scrollTop,
        x: bodyDom.scrollLeft
      }
      this.$confirm('确定取消编辑么,取消编辑讲丢失已编辑的图形?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.pathArr = JSON.parse(JSON.stringify(this.pathArrLast));
        this.isCancelHandle = true;
        polyEditor.setTarget();
        this.drawPolygon();
        this.closePolygon();
        bodyDom.scrollTo(bodyScroll.x, bodyScroll.y)
      }).catch(() => {
        bodyDom.scrollTo(bodyScroll.x, bodyScroll.y)
      });
    },
    //编辑
    startPolygon(type) {
      this.isCancelHandle = false
      this.pathArrLast = JSON.parse(JSON.stringify(this.pathArr));
      if (type === 3) {
        polyEditor.close();
        polyEditor.setTarget();
        polyEditor.open();
      }
      this.type = type;
    },
    campusOk() {
      polyEditor.close();
      console.log(this.pathArr.length);
      if (this.pathArr.length < 1) {
        this.$message({
          message: "请划至少划分一个区域位置！",
          type: "warning",
        });
        return;
      }
      return this.pathArr;
      // this.$emit("onPatharr", this.pathArr); // 在这里将点位合集传给父组件或者请求接口
    },
  },
};
/* eslint-disable */
</script>

<style scoped lang="scss">
#campusMap {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 750px;
  flex: 7;
  position: relative;
}

.campus-page {
  position: relative;
}

.input-card {
  padding: 6px 12px;
  display: flex;
  justify-content: space-between;
  margin: 3px 0;
  align-items: center;
  background-color: var(--color-success-1);
  color: var(--color-success);
}

.red {
  color: rgb(255, 30, 0);
}

.card-flex {
  position: absolute;
  right: 20px;
  top: 20px;
  display: flex;
  justify-content: flex-end;
}

.btn {
  width: 100px;
  display: inline-block;
  font-weight: 400;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  border: 1px solid transparent;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
    border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  background-color: transparent;
  background-image: none;
  color: #25a5f7;
  border-color: #25a5f7;
  background-color: #25a5f7;
  color: #fff;
  padding: 0.25rem 0.5rem;
  line-height: 1.5;
  border-radius: 1rem;
  cursor: pointer;
  margin: 0 5px;
}

.btn:hover {
  color: #fff;
  background-color: #25a5f7;
  border-color: #25a5f7;
}

.btn:hover {
  text-decoration: none;
}

.title {
  border-bottom: 1px solid #ccc;
  padding-bottom: 10px;
  font-size: 18px;
}

.main {
  padding: 20px 20px;
}

:deep(.amap-info-close) {
  font-size: 24px;
  top: 15px;
  right: 17px;
}
</style>
